<template>
	<div class="material">
		<div class="title">
			图片管理
		</div>
		<div class="content-main">
			<div class="toolbar">
				<el-radio-group v-model="rangeRadio" size="mini" @change="rangeSelectChange">
					<el-radio-button :label="-1">全部</el-radio-button>
					<el-radio-button :label="1">收藏</el-radio-button>
				</el-radio-group>

				<div v-show="progress.total" class="progress-wrap" style="display: inline-block;width: 250px;margin-left: 20px;">
					<el-progress :percentage="progress.percentage" :format="progressFormat"></el-progress>
				</div>
				<div class="toolbar-right">
					<span class="count">已上传<i class="num">{{page.total}}</i>张图片</span>
					<el-button type="primary" size="mini" @click="uploadClick">上传图片</el-button>
					<el-upload
            ref="materialUpload"
						multiple
						with-credentials
					  :action="uploadUrl"
					  style="display: none"
					  accept="image/*"
					  :headers="uploadHeaders"
					  :on-change="handleUploadChange"
					  :on-progress="handleUploadProgress"
					>
					  	<el-button size="small" id="uploadImg" ref="uploadImg">点击上传</el-button> 
					</el-upload>
				</div>
			</div>


			<div class="material">
              
              <el-row :gutter="14" v-show="materials.length>0">
                <el-col 
                  v-for="(item,index) in materials" 
                  :key="index" 
                  :sm="12" 
                  :md="8"
                  :lg="6"
                  :xl="4"
                >
                  <el-card class="material-item-wrap" :body-style="cardStyObj">
                  	<div class="material-item">

                    	<el-image
      						style="width: 100%;height: 130px;"
      						:src="item.url"
      						fit="scale-down"
      					></el-image>

      					<div class="img-toolbar">
      						<el-tooltip class="item" effect="dark" content="收藏" placement="left" v-show="item.status == 0">
      							<i class="el-icon-star-off" @click="handleCollect(item)"></i>
      						</el-tooltip>

      						<el-tooltip class="item" effect="dark" content="取消收藏" placement="left" v-show="item.status == 1">
      							<i class="el-icon-star-on" style="color: #ff8100;font-size: 25px;" @click="handleCollect(item)"></i>
      						</el-tooltip>

      						<el-tooltip class="item" effect="dark" content="删除" placement="right">	
      							<i class="el-icon-circle-close" @click="handleDel(item.fileId)"></i>
      						</el-tooltip>	
      					</div>
                  	</div>
                  </el-card>
                  

                </el-col>
              </el-row>

            </div>

            <el-pagination
              class="material-pagination"
              background
              small
              layout="prev,pager,next"
              :page-size="page.pageSize"
              :current-page.sync="page.currentPage"
              :total="page.total"
              @current-change="pageCurChange"
            ></el-pagination>

           
		</div>

	</div>
</template>


<script>
import { getToken } from '@/utils/auth'
import {list, collect, del} from "@/api/material";
import { deepClone } from "@/utils/util";
import { baseUrl } from '@/config/env';


//上传图片的url
const uploadUrl = baseUrl+'/rest/material/image/upload';
//获取图片的url
const imgPrefix = baseUrl+'/rest/material/image/preview/';
export default{

	data(){
		return{
			rangeRadio:-1,
			uploadUrl:uploadUrl,
			uploadHeaders:{'Authorization':'Bearer ' + getToken()},
			//素材库
            materials:[],
            cardStyObj:{
            	'padding':'0px',
            },
            progress:{
            	percentage:0,
            	curCount:0,
            	total:0
            },
            //分页
            page: {
              pageSize: 12,
              currentPage: 1,
              total: 0
            },
		}
	},
	mounted(){
		
		this.getList()
		
	},
	methods:{
		//图片radio切换
		rangeSelectChange(val){
			this.rangeRadio = val;
			this.getList()
		},
		//获取素材
		getList(){
			var params = null
			if(this.rangeRadio == -1){
				params = {
					page:this.page.currentPage,
					limit:this.page.pageSize
				}
			}else{
				params = {
					page:this.page.currentPage,
					limit:this.page.pageSize,
					status:this.rangeRadio
				}
			}

			list(params).then((res)=>{
				console.log("----获取素材列表----")
				console.log(res)
				var result = res.data.data;
				this.page.total = result.total;
				this.materials = this.addUrlWithMaterial(result.records);
			})
		},
		//处理素材库原始数据，添加url
        addUrlWithMaterial(data){
          var imgs = deepClone(data);
          if(imgs.length > 0){
            for(var i=0;i<imgs.length;i++){
              imgs[i]["url"] = imgPrefix + imgs[i].fileId;
              imgs[i]["selected"] = false;
            }
          }

          return imgs;
        },
        //打开图片上传
        uploadClick(){
        	var uploadBtn = window.document.getElementById("uploadImg");
        	uploadBtn.click();
        },
        //文件上传进度条format
        progressFormat(){
        	return `已上传${this.progress.curCount} / ${this.progress.total}`;
        },
        //文件状态改变
        handleUploadChange(file,fileList){
        	console.log("------文件状态改变------")
        	console.log(file)
        	console.log(fileList)
        	if(file.status == "success"){
        		this.progress.curCount ++;
        		if(this.progress.curCount == this.progress.total){
        			this.progress.curCount = 0;
        			this.progress.total = 0;
              //清空upload组件文件
              this.$refs.materialUpload.clearFiles();
        			this.getList();
        		}
        	}
        },
        //文件上传进度条
        handleUploadProgress(event,file,fileList){
        	console.log("------文件上传进度------")
        	console.log(event)
        	console.log(fileList)

          this.progress.percentage = Math.ceil(event.percent);

        	if(this.progress.total == 0){
        		this.progress.total = fileList.length;
        	}
        	
        },
        //删除图片
        handleDel(id){

          this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(()=>{
            return del(id);
          }).then((res) => {

            this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success'
            });
            this.getList();

          }).catch(() => {

            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });


        },
        //页码改变
        pageCurChange(cur){
        	this.page.currentPage = cur;
        	this.getList();
        },
        //收藏
        handleCollect(item){
        	var cur_status = item.status;
        	var fileId = item.fileId;
        	var tar_status = cur_status == 0 ? 1 : 0;
        	collect(fileId,tar_status).then((res)=>{
        		this.$notify({
		          	title: '成功',
		          	message: cur_status == 0 ? '收藏成功' : '取消收藏成功',
		          	type: 'success'
		        });

		        item.status = tar_status;
        	})
        },
        handleCancelCollect(){

        },

	}
}	

</script>


<style>
	
	.progress-wrap .el-progress-bar{
		padding-right: 82px;
		margin-right: -82px;
	}

	.progress-wrap .el-progress__text{
		font-size: 13px!important;
	}

</style>

<style scoped>
	.material{
		padding: 15px;
	}

	.material .title{
		padding: 20px 0;
    padding-top: 0;
		font-size: 16px;
		color: #000;
    font-weight: 700;
    padding-left: 15px;
		border-bottom: 1px solid #eaeaea;
    position: relative;
	}
  .material .title:before{
    position: absolute;
    content: "";
    top: 2px;
    left: 0;
    width: 4px;
    height: 16px;
    background: #ff8100;
  }

	.content-main .toolbar{
		padding: 10px 0;
	}

	.content-main .toolbar .toolbar-right{
		float: right;
	}

	.content-main .toolbar .toolbar-right .count{
		font-size: 13px;
		color: #bababa;
		margin-right: 5px;
	}

	.content-main .toolbar .toolbar-right .count .num{
		margin:0 5px;
		color: #ff8406;
	}

	/*素材容器*/
	.material{
    margin-top: 5px;
  }

  /*素材库图片列表*/
  .material-item-wrap{
  	margin-bottom: 10px;
  	border:1px solid #eaeaea;
  }
  .material-item{
    min-height:180px;
    padding: 2px;
    position: relative;
  }
  .material-item.selected:before{
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: rgba(0,0,0,.5);
    background-image: url();
    -moz-background-size: 40px 40px;
    background-size: 40px 40px;
    background-position: 100% 0;
    background-repeat: no-repeat;
    text-align: center;
    color: #fffacd;
  }
  .material-item:hover{
    border-color:#ff8406;
  }
  .material-item>img{
    width:100%;
  }

  .material-pagination{
    text-align: right;
  }

  .img-toolbar{
  	height: 40px;
  	display: flex;
  	flex-direction: row;
  	justify-content: space-evenly;
  	align-items: center;
  }

  .img-toolbar i{
  	font-size: 20px;
  }
</style>